package com.cn.yugan.Widget.NestedView;


import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.OverScroller;
import android.widget.RelativeLayout;

import com.cn.yugan.Activity.UpinfoActivity;
import com.cn.yugan.mobile.R;
import com.cn.yugan.Utils.DensityUtil;

/**
 * Created by Rover on 2016/8/18 .
 * Email 357319517@qq.com
 *
 */
public class NestedNavLayout extends LinearLayout implements NestedScrollingParent {
    private static final String TAG = "NestedNavLayout";
    public static final int ALPHA_START=0;
    public static final int ALPHA_END=255;
    
    private View mTop;
    private View mNav;
    private ViewPager mViewPager;
    private int mTopViewHeight;

    private OverScroller mScroller;
    private VelocityTracker mVelocityTracker;
    private int mTouchSlop;
    private int mMaximumVelocity, mMinimumVelocity;

    private float mLastY;
    private boolean mDragging;
    private ActionBar mActionBar;
    private Drawable mBgDrawable;
    @Override
    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
        Log.e(TAG, "onStartNestedScroll");
        return true;
    }

    @Override
    public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
        Log.e(TAG, "onNestedScrollAccepted");
    }

    @Override
    public void onStopNestedScroll(View target) {
        Log.e(TAG, "onStopNestedScroll");
    }

    @Override
    public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        Log.e(TAG, "onNestedScroll");
    }

    @Override
    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
        Log.e(TAG, "onNestedPreScroll");
        boolean hiddenTop = dy > 0 && getScrollY() < mTopViewHeight;
        boolean showTop = dy < 0 && getScrollY() >= 0 && !ViewCompat.canScrollVertically(target, -1);

        if (hiddenTop || showTop) {
            scrollBy(0, dy);
            consumed[1] = dy;
        }
    }

    @Override
    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
        return false;
    }

    @Override
    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
                //down - //up+
        if (getScrollY() >= mTopViewHeight) return false;
        fling((int) velocityY);
        return true;
    }

    @Override
    public int getNestedScrollAxes() {
        return 0;
    }



    public NestedNavLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(LinearLayout.VERTICAL);

        mScroller = new OverScroller(context);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mMaximumVelocity = ViewConfiguration.get(context)
                .getScaledMaximumFlingVelocity();
        mMinimumVelocity = ViewConfiguration.get(context)
                .getScaledMinimumFlingVelocity();

    }

    private void initVelocityTrackerIfNotExists() {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
    }

    private void recycleVelocityTracker() {
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mTop = findViewById(R.id.upinfo_middle_rl);
        mNav = findViewById(R.id.upinfo_indicator);
        View view = findViewById(R.id.upinfo_vp);
        if (!(view instanceof ViewPager)) {
            throw new RuntimeException(
                    "id_stickynavlayout_viewpager show used by ViewPager !");
        }
        mViewPager = (ViewPager) view;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //不限制顶部的高度
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        getChildAt(0).measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        ViewGroup.LayoutParams params =  mViewPager.getLayoutParams();
        params.height = getMeasuredHeight() - mNav.getMeasuredHeight();
        setMeasuredDimension(getMeasuredWidth(), mTop.getMeasuredHeight() + mNav.getMeasuredHeight() + mViewPager.getMeasuredHeight());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mTopViewHeight = mTop.getMeasuredHeight()+DensityUtil.dip2px(getContext(),80);
    }


    public void fling(int velocityY) {
        mScroller.fling(0, getScrollY(), 0, velocityY, 0, 0, 0, mTopViewHeight);
        invalidate();
    }

    @Override
    public void scrollTo(int x, int y) {
        if (y < 0) {
            y = 0;
        }
        if (y > mTopViewHeight) {
            y = mTopViewHeight;
        }
        if (y != getScrollY()) {
            updateActionBarAlpha(y * (ALPHA_END - ALPHA_START) / mTopViewHeight + ALPHA_START);
            super.scrollTo(x, y);
        }
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(0, mScroller.getCurrY());
            invalidate();
        }
    }

    public void setActionBarAlpha(int alpha) throws Exception {
        if (mActionBar == null || mBgDrawable == null) {
            throw new Exception("acitonBar is not binding or bgDrawable is not set.");
        }
        mBgDrawable.setAlpha(alpha);
        SpannableString tSS = new SpannableString(mActionBar.getTitle());
        tSS.setSpan(new ForegroundColorSpan(Color.argb(alpha,255,255,255)),0,mActionBar.getTitle().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        mActionBar.setTitle(tSS);
        mActionBar.setBackgroundDrawable(mBgDrawable);
    }

    public void bindingActionBar(ActionBar actionBar) {
        mActionBar = actionBar;
    }

    public void setActionBarBgDrawable(Drawable bgDrawable) throws Exception {
        if (mActionBar == null) {
            throw new Exception("Please try to binding the actionBar before set it's background.");
        }

        mBgDrawable = bgDrawable;
        mBgDrawable.setAlpha(ALPHA_START);
        SpannableString tSS = new SpannableString(mActionBar.getTitle());
        tSS.setSpan(new ForegroundColorSpan(Color.argb(ALPHA_START,255,255,255)),0,mActionBar.getTitle().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        mActionBar.setTitle(tSS);
        mActionBar.setBackgroundDrawable(mBgDrawable);
    }

    void updateActionBarAlpha(int alpha) {
        try {
            setActionBarAlpha(alpha);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    
}
